from flask import request
from flaskapp.entity.House import House
from flaskapp.entity.Star import Star
from flaskapp.entity.User import User
from flaskapp.util.Redprint import Redprint
from flaskapp.util.Result import Result
from flask_jwt_extended import create_access_token, jwt_required, get_jwt_identity
import jwt
import datetime
from flaskapp.util.jwt_optional_for_options import jwt_required1
from flask import request, jsonify
from flaskapp.util.SMSVerification import sms_verification

JWT_SECRET_KEY = "your-secret-key"  # 替换为你的密钥
JWT_ALGORITHM = "HS256"
api = Redprint('users')

#注册
@api.route('/register',methods=['POST'])
def register():
    data = request.json
    print(data)
    account_name = data['accountName']
    username = data['username']
    password = data['password']
    is_admin = False
    new_user = User(account_name,username,password,is_admin)
    new_user.addUser()
    return Result.success(new_user.to_dict(), 'register success')

#登录
@api.route('/login', methods=['POST'])
def login():
    data = request.json
    if 'username' not in data or 'password' not in data:
        return Result.error(400,"Username and password are required")
    username = data['username']
    password = data['password']
    user = User.query.filter_by(username=username).first()
    if user and user.password == password:
        if user.life != 1:
            return Result.error(403, "该用户已被禁用")
        payload = {
            'user_id': user.user_id,
            'username': user.username,
            'is_admin': user.is_admin,
             'exp': datetime.datetime.utcnow() + datetime.timedelta(hours=1)  # 令牌有效期为 1 小时
         }
        access_token = jwt.encode(payload, JWT_SECRET_KEY, algorithm=JWT_ALGORITHM)
        if user.is_admin == 1:
            data = {
                'userid': user.user_id,
                'is_admin': user.is_admin,
                'token': access_token,
                'username': user.account_name
            }
            return Result.success(data, "Login successful and you are the admin")
        else:
            data = {
                'userid': user.user_id,
                'is_admin': user.is_admin,
                'token': access_token,
                'username': user.account_name,
                'phone_verified': user.phone_verified  # 添加手机验证状态
            }
            return Result.success(data, "Login successful and you are not the admin")
    else:
        return Result.error(401, "Invalid username or password")

# 获取当前用户信息（需要token验证）
# @api.route('/current', methods=['GET'])
# @jwt_required()
# def get_current_user():
#     current_user = get_jwt_identity()
#     return Result.success(current_user, "获取用户信息成功")
@api.route('/current', methods=['GET'])
@jwt_required1
def get_current_user():
    # 从请求对象中获取已解码的 payload
    payload = request.jwt_payload
    
    # 获取用户的手机验证状态
    user = User.query.filter_by(user_id=payload['user_id']).first()
    if user:
        payload['phone_verified'] = user.phone_verified
        payload['phone'] = user.phone
    return Result.success(payload, "获取用户信息成功")

@api.route('/aisExist', methods=['POST'])
def aisExist():
    data = request.json
    account_name = data['account_name']
    user = User.query.filter_by(account_name=account_name).first()
    if user is None:
        return Result.error(404, "User not found")
    else:
        return Result.success(True, "User exist")

@api.route('/uisExist', methods=['POST'])
def uisExist():
    data = request.json
    username = data['username']
    user = User.query.filter_by(username=username).first()
    if user is None:
        return Result.error(404, "User not found")
    else:
        return Result.success(True, "User exist")

#获取某用户的收藏房源
@api.route('/getUserStars/<userid>', methods=['GET'])
def getUserStars(userid):
    user = User.query.filter_by(user_id=userid).first()
    stars = Star.query.filter_by(user_id=userid).all()
    houses=[]
    if user is None:
        return Result.error(404, "User not found")
    if stars is not None:
        for star in stars:
            house = House.query.filter_by(house_id=star.house_id).first()
            data = {

            }
            houses.append(data)
        return Result.success(houses)
    else:
        return Result.error(404, "no star house")

# 获取用户详细信息
@api.route('/getUserInfo/<userid>', methods=['GET'])
# @jwt_required()
def get_user_info(userid):
    user = User.query.filter_by(user_id=userid).first()
    if not user:
        return Result.error(404, "用户不存在")
    return Result.success({
        'username': user.username,
        'account_name': user.account_name,
        'user_id': user.user_id,
        'is_admin': user.is_admin,
        'phone': user.phone,
        'phone_verified': user.phone_verified
    }, "获取用户信息成功")

#修改用户信息
@api.route('/updateUserInfo', methods=['POST'])
def update_user_info():
    user_id = request.args.get('user_id', type=int)
    data = request.json
    # 获取当前用户
    user = User.query.filter_by(user_id=user_id).first()
    if not user:
        return Result.error(404, "用户不存在")
    # 验证旧密码
    old_password = data.get('old_password')
    if not old_password or user.password != old_password:
        return Result.error(401, "原密码错误")
    if 'username' in data:
        if data['username'] == user.username:
            return Result.error(400, "此账号与原账号相同")
        existing_user = User.query.filter(
            User.username == data['username'],
            User.user_id != user_id
        ).first()
        if existing_user:
            return Result.error(400, "此账号已被其他用户使用")
        
        User.update_username(user_id,data['username'])
        return Result.success(True, "账号修改成功")

    if 'account_name' in data:
        if data['account_name'] == user.account_name:
            return Result.error(400, "此账户名与原账户名相同")
        existing_user = User.query.filter(
            User.account_name == data['account_name'],
            User.user_id != user_id
        ).first()
        if existing_user:
            return Result.error(400, "此账户名已被其他用户使用")
        User.update_account_name(user_id,data['account_name'])
        return Result.success(True, "账户名修改成功")

    if 'password' in data:
        User.update_password(user_id, data['password'])
        return Result.success(True, "密码修改成功")

    return Result.error(400, "没有输入信息")

# 获取租客详细信息
@api.route('/tenant-info/<int:tenant_id>', methods=['GET'])
def get_tenant_info(tenant_id):
    tenant = User.query.filter_by(user_id=tenant_id).first()
    if tenant:
        return Result.success({
            'account_name': tenant.account_name,
            'phone': tenant.phone
        }, "获取租客信息成功")
    else:
        return Result.error(404, "租客不存在")

# 发送手机验证码
@api.route('/send-sms-code', methods=['POST'])
@jwt_required1
def send_sms_code():
    data = request.json
    phone = data.get('phone')
    
    # 从请求对象中获取已解码的 payload
    payload = request.jwt_payload
    user_id = payload.get('user_id')
    
    if not phone:
        return Result.error(400, "手机号不能为空")
    
    # 检查手机号格式（简单验证）
    if not phone.isdigit() or len(phone) != 11:
        return Result.error(400, "手机号格式不正确")
    
    # 发送验证码
    success, message = sms_verification.send_code(phone)
    
    if success:
        return Result.success(None, message)
    else:
        return Result.error(500, message)

# 验证手机号
@api.route('/verify-phone', methods=['POST'])
@jwt_required1
def verify_phone():
    data = request.json
    phone = data.get('phone')
    code = data.get('code')
    
    # 从请求对象中获取已解码的 payload
    payload = request.jwt_payload
    user_id = payload.get('user_id')
    
    if not phone or not code:
        return Result.error(400, "手机号和验证码不能为空")
    
    # 验证验证码
    success, message = sms_verification.verify_code(phone, code)
    
    if success:
        # 更新用户手机号和验证状态
        if User.update_phone(user_id, phone, True):
            return Result.success(None, "手机号验证成功")
        else:
            return Result.error(404, "用户不存在")
    else:
        return Result.error(400, message)

# 检查用户是否已验证手机号
@api.route('/check-phone-verified', methods=['GET'])
@jwt_required1
def check_phone_verified():
    # 从请求对象中获取已解码的 payload，而不是重新解码 token
    # 因为 jwt_required1 装饰器已经解码并存储了 payload
    payload = request.jwt_payload
    user_id = payload.get('user_id')
    
    user = User.query.filter_by(user_id=user_id).first()
    if not user:
        return Result.error(404, "用户不存在")
    
    return Result.success({
        'phone_verified': user.phone_verified,
        'phone': user.phone
    }, "获取手机验证状态成功")